package com.javaer666.algorithm;

import com.google.common.collect.Range;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingValue;
import org.apache.shardingsphere.sharding.exception.syntax.UnsupportedShardingOperationException;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: bj910
 * Date:2023-09-02
 * Time: 7:07
 * To change this template use File | Settings | File Templates.
 */
public class MyAlgorithm implements ComplexKeysShardingAlgorithm<Long> {
    public static final String SHARING_COLUMNS_KEY = "sharding-columns";
    private Properties props;
    //保留配置的分片键。在当前算法中其实是没有用的。
    private Collection<String> shardingColumns;

    public Collection<String> getShardingColumns(final Properties props) {
        String property = props.getProperty(SHARING_COLUMNS_KEY, "");
        return property.isEmpty()? Collections.emptyList(): Arrays.asList(property.split(","));
    }

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, ComplexKeysShardingValue<Long> shardingValue) {
        //select * from course where cid in() and user_id   between {lowerEndpoint} and {upperEndpoint};
        Collection<Long> cidCol = shardingValue.getColumnNameAndShardingValuesMap().get("cid");
        Range<Long> userIdRange = shardingValue.getColumnNameAndRangeValuesMap().get("user_id");

        Long lowerEndpoint = userIdRange.lowerEndpoint();
        Long upperEndpoint = userIdRange.upperEndpoint();

        if (lowerEndpoint>upperEndpoint){
            throw new UnsupportedShardingOperationException("empty record query","course");
        }else if (upperEndpoint<1001L || lowerEndpoint>1001L){
            throw new UnsupportedShardingOperationException("error range query param","course");
        }else {
            List<String> result = new ArrayList<>();
            String logicTableName = shardingValue.getLogicTableName();
            for (Long cidVal : cidCol) {
                String s = logicTableName + "_" + (cidVal % 2 + 1);
                if (availableTargetNames.contains(s)){
                    result.add(s);
                }
            }
            return result;
        }
    }

    @Override
    public Properties getProps() {
        return this.props;
    }

    public void setProps(Properties props) {
        this.props = props;
    }

    @Override
    public void init(Properties props) {
        this.props = props;
        this.shardingColumns = getShardingColumns(props);
    }

    @Override
    public String getType() {
        return "MYCOMPLEX";
    }
}
